package com.woniuxy.java106crm.interceptor;

import com.woniuxy.java106crm.annotation.RequireMethod;
import com.woniuxy.java106crm.entity.LogManage;
import com.woniuxy.java106crm.service.LogManageService;
import com.woniuxy.java106crm.util.WebUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

/**
 * 拦截静态资源、controller
 */
@Slf4j
@Component
public class ControllerInterceptor implements HandlerInterceptor {

    @Resource
    private LogManageService logManageService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        log.info("拦截器执行拦截");
//        log.info(handler.getClass().toString());
        //如果请求的是方法
        if(handler instanceof HandlerMethod){
            //得到方法
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
//            log.info(method.toString());
            //判断方法上是否有自定义注解
            if(method.isAnnotationPresent(RequireMethod.class)){
                log.info("有注解");
                RequireMethod requirePerms = method.getAnnotation(RequireMethod.class);
                //获得注解里面的内容
                String control = requirePerms.value();
//                log.info(control);
                //获得当前用户的用户名
                String account = (String) request.getSession().getAttribute("account");
//                log.debug("当前用户的用户名：{}",account);
                LogManage manage = new LogManage();
                manage.setMethod(String.valueOf(handlerMethod));
                manage.setController(control);
                manage.setUsername(account);
                manage.setDate(LocalDateTime.now());
                manage.setIp(WebUtil.getHttpServletRequest().getRemoteAddr());
//                System.out.println("manage = "+manage)
                logManageService.addLogManage(manage);
            }else{
                log.info("没有注解");
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
